<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="填入项目名称(选填)" v-model="projectNameSearch"></el-input>
      <el-select v-model="creatorSearch" filterable placeholder="选择创建人" style="width: 150px; margin: 0 5px">
        <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="recipientSearch" filterable placeholder="选择接收人" style="width: 150px; margin: 0 5px">
        <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="success" @click="reset">刷新</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAddOrEdit">新增项目</el-button>
      <el-button type="danger" plain @click="handleDelBatch">批量删除</el-button>
      <el-button type="success" plain @click="handleDelBatch">统计看板</el-button>
    </div>
    <!--  整个表格，有多选框 -->
    <el-table v-loading="loading" element-loading-text="拼命加载中" :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue',color: '#666'}"
              @selection-change="handleSelectionChange">
      <!--    复选框-->
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="projectNum" label="项目编号" width="100px"></el-table-column>
      <el-table-column prop="projectName" label="项目名称" width="100" ></el-table-column>
      <el-table-column prop="projectTag" label="项目标签" width="100"></el-table-column>
      <el-table-column prop="projectDescription" label="项目简述" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="attachName" label="附件名称" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="recipientName" label="正在处理" width="100"></el-table-column>
      <!-- <el-table-column prop="auditorName" label="审核人" width="100"></el-table-column> -->
<!--      <el-table-column prop="state" label="状态" width="80"></el-table-column>-->
      <el-table-column prop="state" label="当前状态(点击查明细)" width="180">
        <template v-slot="scope">
          <el-button @click="previewAuditRecord(scope.row)" :type="getStatusType(scope.row)">{{getStatusText(scope.row)}}</el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="expirationTime" label="结束时间" width="100"></el-table-column> -->
      <el-table-column prop="creatTime" label="创建时间" width="140"></el-table-column>
      <el-table-column prop="creatorName" label="创建人" width="100"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="140"></el-table-column>
      <el-table-column prop="modifierName" label="更新人" width="100"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="180px">
        <template v-slot="scope">
          <el-button v-if="allowEdit(scope.row)"size="mini" type="primary" plain @click="handleAddOrEdit(scope.row)">编辑</el-button>
<!--          <el-button v-if="isAudit(scope.row)" size="mini" type="info" plain @click="handleDel(scope.row)">删除</el-button>-->
          <el-button v-if="isAudit(scope.row)" size="mini" type="info" plain @click="openAudit(scope.row)">审核</el-button>
          <!-- <el-button v-if="isRecipient(scope.row)" size="mini" type="success" plain @click="handleConfirm(scope.row)">接收</el-button> -->
           
           <!-- <el-button v-if="isRecipient(scope.row)" size="mini" type="success" plain @click="handleConfirm(scope.row)">确认完成</el-button> -->
           <!-- <el-button size="mini" type="info" plain @click="openAudit(scope.row)">审核</el-button> -->
           <el-button v-if="allowEdit(scope.row)" size="mini" type="success" plain @click="openConfirm(scope.row)">确认</el-button>
           <el-button v-if="isStart(scope.row.currentStep)" size="mini" type="success" plain @click="openConfirm(scope.row)">开始</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0;text-align: center">
      <el-pagination @current-change="handleCurrentChange"
                     :current-page="pageNum"
                     :page-size="pageSize"
                     layout="total,prev,pager,next"
                     :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="editTitle"
               :visible.sync="formVisible"
               width="90%"
               :close-on-click-model="false">
      <el-steps :active="currentStep-1" finish-status="success" style="margin-bottom: 20px">
        <el-step v-for="step in steps" :key="step.step" :title="step.stepName"></el-step>
      </el-steps>
      <el-form :model="form"
               label-width="80px"
               style="padding-right: 20px"
               :rules="rules"
               ref="formRef">
        <!-- 新增模式显示流程模板选择，编辑模式不显示 -->
        <el-form-item v-if="!isEditMode" label="流程模板" prop="templateId">
          <el-select v-model="form.templateId" filterable placeholder="请选择流程模板" @change="handleTemplateChange">
            <el-option v-for="template in templates" :key="template.id" :label="template.templateName" :value="template.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目编号" prop="projectNum">
          <div style="display: flex; align-items: center;">
            <!-- 编辑模式下不可修改，新增模式下根据autoGenerateNum决定是否可编辑 -->
            <el-input v-model="form.projectNum" placeholder="如：sg1001" :disabled="isEditMode || autoGenerateNum"></el-input>
            <!-- 仅在新增模式下显示自动编号选项 -->
            <el-checkbox v-if="!isEditMode" v-model="autoGenerateNum" @change="handleAutoGenerateNumChange" style="margin-left: 10px;">自动编号</el-checkbox>
          </div>
        </el-form-item>

        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="如：金刚石项目"></el-input>
        </el-form-item>

        <el-form-item label="项目标签" prop="projectTag">
          <el-input v-model="form.projectTag" placeholder="选填，后期计划改为下拉选择"></el-input>
        </el-form-item>

        <!-- prop 与rules字段绑定     -->
        <el-form-item label="项目简述" prop="projectDescription">
          <el-input type="textarea" v-model="form.projectDescription" placeholder="选填，简单描述这个项目"></el-input>
        </el-form-item>

        <el-form-item label="附件" prop="attachName">
          <el-input v-model="form.attachName" placeholder="暂无附件" :readonly="true"></el-input>
          <!-- <div style="margin: 15px;text-align: center">
            <el-upload ref="uploader" class="upload-demo" :action="this.$apiUrl+'/file/upload'" :headers="{token: user.token}" :file-list="fileList" :on-preview="handlePreview" :on-success="handleOnSuccess" :before-upload="beforeUpload" :before-remove="beforeRemoved" multiple :limit="3" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">注意：单个附件安全范围是100MB以内</div>
            </el-upload>
          </div> -->
          <div style="margin: 15px;text-align: center">
            <!-- :on-change="handleChange" -->
            <el-upload ref="uploader"
                class="upload-demo"
                :action= "this.$apiUrl+'/file/upload'"
                :headers="{token: user.token}"
                :file-list="fileList"
                :on-preview="handlePreview"
                :on-success="handleOnSuccess"
                :before-upload="beforeUpload"
                :before-remove="beforeRemoved"
                multiple
                :limit="30"
                :on-exceed="handleExceed"
                :drag="true"
                @drop="handleDrop"
                @dragover.prevent
            >
              <div class="el-upload__tip">将文件拖到此处，或<em>点击上传</em></div>
              <div slot="tip" class="el-upload__tip">注意：单个文件安全范围是100MB以内</div>
            </el-upload>
          </div>
        </el-form-item>

        <!-- <el-form-item label="下一人" prop="recipient">
          <el-select v-model="form.recipient" filterable placeholder="按流程选择" :options="userOptions" value-key="value" style="width: 150px; margin: 0 5px">
            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="接收人" prop="recipient">
          <el-select v-model="form.recipient" filterable placeholder="选填" :options="userOptions" value-key="value" style="width: 150px; margin: 0 5px">
            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item> -->

<!--        <el-form-item label="审核人" prop="content">-->
<!--          <el-input v-model="form.auditorName" placeholder="默认赵总"></el-input>-->
<!--        </el-form-item>-->

        <!-- <el-form-item label="到期时间" prop="expirationTime">
          <template>
            <div class="block">
              <span class="demonstration"></span>
              <el-date-picker
                  v-model="form.expirationTime"
                  type="date"
                  placeholder="选择日期">
              </el-date-picker>
            </div>
          </template>
        </el-form-item> -->

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="审核意见" :visible.sync="auditVisible" width="40%">
      <div style="margin: 0 auto;text-align: center">
        <span style="font-weight: bold;font-size: 20px">请检查以下待审核信息：</span>
      </div>
      <template>
        <!-- <div style="margin-top: 20px; margin-bottom: 20px;">
          <el-radio-group v-model="radioSize">
            <el-radio label="medium">大</el-radio>
            <el-radio label="small">中</el-radio>
            <el-radio label="mini">小</el-radio>
          </el-radio-group>
        </div> -->

        <el-steps :active="auditForm.currentStep-1" finish-status="success" style="margin-bottom: 20px">
          <el-step v-for="step in steps" :key="step.step" :title="step.stepName"></el-step>
        </el-steps>

        <el-descriptions :column="2" :size="radioSize" border>
<!--          <template slot="extra">-->
<!--            <el-button type="primary" size="small">操作</el-button>-->
<!--          </template>-->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              项目编号
            </template>
            {{auditForm.projectNum}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              项目名称
            </template>
            {{auditForm.projectName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-location-outline"></i>
              项目标签
            </template>
            {{auditForm.projectTag}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets"></i>
              项目简述
            </template>
            {{auditForm.projectDescription}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              附件
            </template>
            <el-upload ref="uploader" class="upload-demo" :action="this.$apiUrl+'/file/upload'" :file-list="fileList" :on-preview="handlePreview" :before-remove="beforeRemovedAudit" multiple :limit="30">
            </el-upload>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              审核人
            </template>
            {{auditForm.recipientName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              到期时间
            </template>
            {{auditForm.expirationTime}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              备注
            </template>
            {{auditForm.remark}}
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 15px;">
          <label style="display: block; margin-bottom: 8px;">留言内容：</label>
          <el-input
            v-model="auditForm.confirmMessage"
            type="textarea"
            placeholder="留言（选填）"
            :rows="3"
          ></el-input>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="auditVisible=false">关闭</el-button>
        <el-button type="danger" plain @click="reject">拒绝</el-button>
        <el-button type="success" plain @click="pass">同意</el-button>
      </span>
    </el-dialog>

    <el-dialog title="确认信息" :visible.sync="confirmVisible" width="50%">
      <div style="margin: 0 auto;text-align: center">
        <span style="font-weight: bold;font-size: 20px;">请检查以下待确认信息：</span>
      </div>
      <template>
        <el-steps :active="confirmForm.currentStep-1" finish-status="success" style="margin-bottom: 20px">
          <el-step v-for="step in steps" :key="step.step" :title="step.stepName"></el-step>
        </el-steps>
        <el-descriptions :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-coordinate"></i>
              项目编号
            </template>
            {{confirmForm.projectNum}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-warning-outline"></i>
              项目名称
            </template>
            {{confirmForm.projectName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-collection-tag"></i>
              项目标签
            </template>
            {{confirmForm.projectTag}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets"></i>
              项目描述
            </template>
            {{confirmForm.projectDescription}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-folder-opened"></i>
              附件
            </template>
            <el-upload ref="uploader" class="upload-demo" :action="this.$apiUrl+'/file/upload'" :file-list="fileList" :on-preview="handlePreview" :before-remove="beforeRemovedAudit" multiple :limit="30">
            </el-upload>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              归属人
            </template>
            {{confirmForm.recipientName}}
          </el-descriptions-item>
          <!-- <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              到期时间
            </template>
            {{auditForm.expirationTime}}
          </el-descriptions-item> -->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-document"></i>
              备注
            </template>
            {{confirmForm.remark}}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 确认留言输入框 -->
        <div style="margin-top: 15px;">
          <label style="display: block; margin-bottom: 8px;">留言内容：</label>
          <el-input
            v-model="confirmForm.confirmMessage"
            type="textarea"
            placeholder="留言（选填）"
            :rows="3"
          ></el-input>
        </div>
        
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmVisible=false">关闭</el-button>
        <el-button type="success" plain @click="handleConfirm(confirmForm)">确认</el-button>
      </span>
    </el-dialog>

    <!-- 预览图片 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="60%" :src="dialogImageUrl">
    </el-dialog>

    <el-dialog title="流程明细" :visible.sync="auditRecordVisible" width="60%">
      <!-- 将active从currentStep改为currentStep-1，因为组件索引从0开始而业务逻辑从1开始 -->
      <el-steps :active="currentStep - 1" finish-status="success" style="margin-bottom: 20px;">
        <el-step v-for="step in steps" :key="step.step" :title="step.stepName"></el-step>
      </el-steps>
      <!-- 默认显示的活动记录 -->
      <div v-if="!showApiActivities">
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :icon="activity.icon"
            :type="activity.type"
            :size="activity.size"
            :timestamp="activity.timestamp"
            placement="top"
          >
            <el-card>
              <h4>{{ activity.title }}</h4>
              <p>{{ activity.description }}</p>
              <p>负责人：{{ activity.handler }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <!-- 从接口获取的活动记录 -->
      <div v-else>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in apiActivities"
            :key="index"
            :icon="activity.icon || 'el-icon-loading'"
            :type="activity.type || 'primary'"
            :size="activity.size || 'small'"
            :timestamp="activity.timestamp || ''"
            placement="top"
          >
            <el-card>
              <h4>{{ activity.title }}</h4>
              <p>{{ activity.description }}</p>
              <p>负责人：{{ activity.handler }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        
        <!-- 如果没有从接口获取到数据，显示提示信息 -->
        <div v-if="apiActivities.length === 0 && !loading" style="text-align: center; color: #909399; padding: 20px;">
          暂无活动记录
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button v-if="showApiActivities" @click="handleViewLocalRecords">查看流程记录</el-button>
        <el-button v-if="!showApiActivities" @click="handleViewDetailRecords">查看明细记录</el-button>
        <el-button @click="handleCloseAuditRecord">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {    
    name: "ProjectPro",
    data(){
    return {
      tableData: []//表数据
      ,loading: true
      ,pageNum: 1//当前页码
      ,pageSize: 15//每页数量
      ,projectNameSearch: ''
      ,creatorSearch: ''
      ,recipientSearch: ''
      ,content: ''
      ,total: 0 //数据总条数
      ,formVisible: false //默认不显示新增表单弹窗
      ,auditVisible: false //默认不显示审核意见弹窗
      ,confirmVisible: false //默认不显示确认弹窗
      ,auditRecordVisible: false //默认不显示审核记录弹窗
      ,form: {}
      ,auditForm:{}
      ,confirmForm:{}
      ,confirmMessage: '' //确认时的留言内容
      ,user: JSON.parse(localStorage.getItem('userInfo') || '{}')
      ,rules: {
        projectNum: [
          {required: () => !this.autoGenerateNum, message: '输入项目编号', trigger: 'blur'}
        ],
        projectName: [
          {required: true,message: '输入项目名称',trigger: 'blur'}
        ],
        recipient: [
          {required: true,message: '选择接收人',trigger: 'blur'}
        ],
        templateId: [
          {required: true, message: '请选择流程模板', trigger: 'change'}
        ]
      }
      ,autoGenerateNum: false //自动编号开关
      ,currentStep: 0 //当前步骤
      ,ids: []
      ,userOptions: []
      ,expirationTime: '' //到期时间
      ,auditSate: [1,3,5] //正在审核的状态码
      ,auditors: [44,46] //有权审核的人
      ,editTitle: ''
      ,fileList: []
      ,attachIds: []
      ,radioSize: ''
      ,dialogImageUrl: '' //图片预览对话框图片地址
      ,dialogVisible: false//图片预览对话框
      // 流程模板相关
      ,templates: [] //模板列表
      ,templatesLoaded: false //模板是否加载完成
      ,isEditMode: false //是否为编辑模式
      // 步骤数据，方便维护
      ,steps: []
      // 活动数据，根据currentStep动态生成样式
      ,activities: []
      // 从接口获取的活动记录
      ,apiActivities: []
      // 是否显示从接口获取的活动记录
      ,showApiActivities: false
      // 当前项目ID
      ,currentProjectId: null,
    }
  },
  created() {
    this.load();
    // 加载模板列表
    this.loadTemplates();
  },
  //安装
  mounted() {
    this.initUsersOptions()
    // this.generateActivities()
  },
  watch: {
    // 监听确认对话框可见性变化，关闭时清空留言内容
    confirmVisible(newValue) {
      if (!newValue) {
        this.confirmForm.confirmMessage = '';
      }
    },
  },
  methods: {
    // 加载模板列表
    loadTemplates() {
      this.loading = true;
      this.$request({
        method: 'GET',
        url: '/processNode/getTemplateList'
      }).then(res => {
        if (res.code === '200') {
          this.templates = res.data;
          this.templatesLoaded = true;
        } else {
          this.$message.error(res.msg || '获取模板列表失败');
          console.error('获取模板列表失败，响应码:', res.code);
        }
      }).catch(error => {
        this.$message.error('获取模板列表失败: ' + error.message);
        console.error('获取模板列表异常:', error);
      }).finally(() => {
        this.loading = false;
      });
    },
    // 模板选择框变化，刷新步骤列表
    handleTemplateChange(val) {
      this.form.templateId = val;
      // 重置当前步骤为0
      this.currentStep = 0;
      this.loadSteps();
    },
    //从结构获取节点数据
    getSteps(templateId){
      this.$request({
        method: 'GET',
        url: '/processNode/getStepsList',
        params: {
          templateId: templateId
        }
      }).then(res => {
        if (res.code === '200') {
          // 确保步骤数据使用stepName属性
          if (Array.isArray(res.data)) {
            this.steps = res.data.map(step => {
              // 如果步骤对象有name属性但没有stepName属性，则将name值赋给stepName
              if (step.name && !step.stepName) {
                return { ...step, stepName: step.name };
              }
              return step;
            });
          } else {
            this.steps = [];
            this.$message.warning('未获取到有效的步骤数据');
          }
        } else {
          this.$message.error(res.msg || '加载模板失败');
          this.steps = []; // 清空步骤数据
        }
      }).catch(error => {
        this.$message.error('加载模板失败: ' + error.message);
        this.steps = []; // 清空步骤数据
      }).finally(() => {
        this.loading = false;
      });
    },
    // 加载流程
    loadSteps() {
      if (!this.form.templateId) {
        this.$message.warning('请先选择模板');
        this.steps = [];
        return;
      }
      this.loading = true;
      this.getSteps(this.form.templateId);
    },
    // 生成活动数据
    generateActivities() {
      // 显示加载状态
      this.loading = true;
      try {
        // 从this.steps中生成活动数据（已从row.stepsJson设置）
        if (this.steps && Array.isArray(this.steps)) {
          // 根据步骤数据生成活动记录
          this.activities = this.steps.map((step, index) => {
            // 确定活动类型和图标（根据步骤是否已完成）
            const isCompleted = step.step < this.currentStep;
            return {
              icon: isCompleted ? 'el-icon-check' : 'el-icon-loading',
              type: isCompleted ? 'success' : 'primary',
              size: 'small',
              timestamp: step.stepTime || '',
              title: step.stepName || ` ${step.step}`,
              description: step.description || ` ${step.step}`,
              handler: step.handlerName || '未知'
            };
          });
        } else {
          this.activities = [];
        }
      } catch (error) {
        this.$message.error('生成活动数据失败: ' + error.message);
        this.activities = [];
      } finally {
        // 隐藏加载状态
        this.loading = false;
      }
    },
    //上传文件组件
    handleDrop(event) {
      event.preventDefault();
      // 可以根据需求添加文件处理逻辑
      console.log('文件已拖拽放下', event.dataTransfer.files);
    },
    //上传文件组件，限制附件个数
    handleExceed(files, fileList) {
      this.$message.warning(
          `当前限制选择 3 个附件，本次选择了 ${
              files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    //上传文件组件，成功后记录文件名和文件路径
    handleOnSuccess(response, file, fileList) {
      this.fileList = fileList
      this.attachIds.push(response.data.id)
      //改变附件名称
      this.updateAttachNameAndId()
    },
    //更新附件名称和附件ID
    updateAttachNameAndId(){
      this.form.attachName = this.fileList
          .map((file) => file.name)
          .join('，')
      this.form.attachIds = this.attachIds.map(id => `${id}`).join('，');
    },
    //上传组件，移除元素之前
    beforeRemoved(file, fileList) {
      if (file && file.status === 'success') {
        this.$confirm(`确定移除【${file.name}】吗？`)
            .then(() => {
              //刷新一下全局变量
              this.fileList = fileList
              if (this.fileList.length < 1){
                this.attachIds = []; //重置一下
              }
              this.attachIds = this.attachIds.filter(i => i !== file.response.data.id);
              //确认移除,改变附件名称和附件ID
              this.updateAttachNameAndId()
              return true
            })
            .catch(() => {
              //取消或关闭
              return false
            })
      }
    },
    //审核预览附件，点击移除时
    beforeRemovedAudit(file, fileList) {
      // this.$message.warning("当前是审核页，移除附件请到编辑页操作，本次移除动作不做保留。若需改动系统设计请联系林硕修改")
      this.$notify({
        title: '系统功能讲解：',
        message: '你若是想预览文件，请点击文件名称即可预览。你若是想移除这个文件，请到编辑页操作移除。本次移除的文件仅在当前审核页消失，实际上系统没有移除这个文件，你再次打开还能看到。若需改动系统设计请联系林硕修改。',
        duration: 0
      })
    },
    //上传文件之前
    beforeUpload(file) {
      let size = file.size
      let maxSize = 100 * 1024 * 1024
      if (size > maxSize) {
        // this.$message.warning("附件大小不能超过100MB")
        // return false
        // this.$refs.uploader.abort() //终止上传
        return this.$confirm(
            '当前附件【' +
            file.name +
            '】文件大小超出100MB安全范围，继续上传可能会出错，请确认是否继续上传？',
            '警告提示'
        )
      }
    },
    //上传文件组件，文件预览
    handlePreview(file) {
      const imageExtensions = [
        'jpg',
        'jpeg',
        'png',
        'gif',
        'bmp',
        'tiff',
        'webp',
      ]
      let fileExtensionMatch = file.response.data.fileName.match(/\.([^\.]+)$/)
      let fileExtension = fileExtensionMatch ? fileExtensionMatch[1] : '' //文件扩展名
      if (imageExtensions.includes(fileExtension.toLowerCase())) {
        // this.$message.warning('预览图片功能正在开发中……')
        this.dialogImageUrl = file.response.data.fileUrl;
        this.dialogVisible = true;
      } else {
        this.$message.warning('选中的文件不是图片，暂不支持预览')
      }
    },
    /**
     * 处理审批拒绝逻辑
     * 当拒绝时，将当前步骤回退，并检查回退后的步骤是否为审批步骤，若是则继续回退
     */
    reject(){
      // 验证auditForm数据完整性
      if (!this.auditForm || typeof this.auditForm.currentStep !== 'number' || !this.auditForm.stepsJson || !Array.isArray(this.auditForm.stepsJson)) {
        this.$message.error('审批表单数据不完整或无效');
        return;
      }
      this.auditForm.isPass = false; //未通过
      // 回退到上一个步骤
      let currentStep = this.auditForm.currentStep - 1;
      let stepConfig;
      const minStep = 1; // 假设最小步骤为1
      while (currentStep > minStep) {
        // 查找当前步骤的配置
        stepConfig = this.auditForm.stepsJson.find(step => step.step === currentStep);
        if (!stepConfig) {
          console.log(`未找到步骤 ${currentStep} 的配置，停止回退`);
          break;
        }
        if (stepConfig.stepType === 2) {
          // 如果是审批步骤，回退1步
          currentStep -= 2;
        } else {
          // 如果是非审批步骤，结束循环
          currentStep -= 1;
          break;
        }
      }
      // 确保步骤不会小于最小步骤数
      if (currentStep < minStep) {
        currentStep = minStep;
        console.log(`已回退到最小步骤 ${minStep}`);
      }
      // 如果没有找到任何有效步骤配置
      if (!stepConfig) {
        console.log('拒绝-回退过程中未找到有效步骤配置');
      }
      // 更新当前步骤
      this.auditForm.currentStep = currentStep;
      // 执行确认操作并关闭审核窗口
      this.handleConfirm(this.auditForm);
      this.auditVisible = false;
    },
    //审批通过
    pass(){
      this.auditForm.isPass = true;
      this.handleConfirm(this.auditForm)
      this.auditVisible = false;
    },
    reset(){
      this.projectName = ''
      this.creator = ''
      this.recipient = ''
      this.load()
    },
    load(pageNum){
      this.loading = true;
      if (pageNum) this.pageNum = pageNum;  //分页查询时自动切换到第一页
      this.$request.get('/projectPro/findByPage',{
        params:{
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          projectName: this.projectNameSearch,
          creator: this.projectNameSearch,
          recipient: this.projectNameSearch
        }
      }).then(res => {
        if (res.data){
          if (res.data.records){
            // this.tableData = res.data
            this.tableData = res.data.records  //若records不显示可替换为List
          }else{
            this.$message.warning("res.data.records不存在")
          }
          this.total = res.data.total
        }else {
          this.$message.error("接口未返回数据，请联系管理员!")
          // this.$router.push('/login')
        }
        this.loading = false
      })
    },
    //切换页码
    handleCurrentChange(pageNum){
      // this.pageNum = pageNum //方法传递过来参数就不用赋值了
      this.load(pageNum)
    },
    //新增弹窗事件||编辑弹窗
    handleAddOrEdit(row){
      //判断是否编辑模式，默认false
      if (row.id){
          //编辑模式显示编辑信息
          this.editTitle = '编辑信息'
          this.isEditMode = true;
          this.form = JSON.parse(JSON.stringify(row)) //弹窗带出来信息,浅拷贝是内存指向，深拷贝是开区域赋值
          //确保currentStep存在且为数字类型
          this.form.currentStep = Number(this.form.currentStep) || 0;
          //同步当前步骤
          this.currentStep = this.form.currentStep;
          //设置模板ID并加载步骤
          this.form.templateId = row.templateId || '';
          this.steps = row.stepsJson;
          //需要把upload组件的fileList带出来
          if (this.form.fileListJson) {
            this.fileList = this.form.fileListJson
          } else {
            this.fileList = []
          }
      } else {
        //新增模式显示新增信息
          this.editTitle = '新增信息'
          this.autoGenerateNum = false
          this.isEditMode = false; //其实不用写，默认就是false
          this.form = {}; //新增数据时清空表单
          this.form.currentStep = 0; //默认设置流程步骤为1
          this.steps = []; //清空步骤数据
        }
      this.formVisible = true //显示弹窗
    },
    //明细记录
    previewAuditRecord(row){
      this.auditRecordVisible = true;
      this.currentStep = row.currentStep; // 设置当前步骤
      this.currentProjectId = row.id; // 保存项目ID
      // 设置步骤数据，确保el-steps能正确显示
      this.steps = row.stepsJson || [];
      this.generateActivities(); // 重新生成活动记录
      // 默认为false，显示本地activities数据
      this.showApiActivities = false;
      // 初始化apiActivities为空数组
      this.apiActivities = [];
    },
    
    // 查看明细记录按钮点击事件
    handleViewDetailRecords() {
      // 只有点击按钮时才调用接口获取数据
      this.showApiActivities = true;
      this.getActivitiesFromApi(this.currentProjectId);
    },
    handleViewLocalRecords() {
      this.showApiActivities = false;
    },
    
    // 从接口获取活动记录
    getActivitiesFromApi(projectId){
      this.loading = true;
      this.$request({
        method: 'GET',
        url: '/projectPro/getActivities',
        params: {
          projectId: projectId
        }
      }).then(res => {
        if (res.code === '200') {
          // 假设接口返回的数据格式与activities的数据格式一致
          this.apiActivities = res.data || [];
        } else {
          this.$message.error(res.msg || '获取活动记录失败');
          this.apiActivities = [];
        }
      }).catch(error => {
        this.$message.error('获取活动记录异常: ' + error.message);
        this.apiActivities = [];
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 重置显示状态
    resetShowState() {
      this.showApiActivities = false;
      this.apiActivities = [];
    },
    
    // 处理关闭审核记录弹窗
    handleCloseAuditRecord() {
      this.auditRecordVisible = false;
      this.resetShowState();
    },
    //保存之前状态流转修改
    beforeSaveUpdateState(){
      // switch (this.form.state){
      //   case 2: //待起草 --> 待初步工程图审核
      //     this.form.state = 3;
      //     break;
      //   case 21: //待修改立项 - 待立项审核
      //     this.form.state = 1;
      //     break;
      //   case 4 : //待细化 - 待细化审核
      //     this.form.state = 5;
      //     break;
      //   case 41 : //待修改工程图 - 待工程图审核
      //     this.form.state = 3;
      //     break;
      //   case 61 : //待修改细化工程图 - 待细化工程图审核
      //     this.form.state = 5;
      //     break;
      //   case 7 : //已接收 - 待初步工程图审核
      //     this.form.state = 3;
      //     break;
      //   default: //无论是新增还是编辑，初始状态都是1，但若编辑前已经有进行中的其他状态，则顺延状态。
      //     this.form.state = 1;
      //     break;
      // }
    },
    //发送save请求
    sendSave(){
      // this.beforeSaveUpdateState();
      // 检查 currentStep 是否为数字类型（包括 0）
      if(typeof this.currentStep === 'number'){
        this.form.currentStep = this.currentStep;
      }else{
        this.$message.error("步骤参数不存在");
        return;
      }
      
      //发送请求
      this.$request({
        //有id就是编辑
        method: this.form.id ? 'PUT' : 'POST',
        data: {...this.form},
        url: this.form.id ? '/projectPro/update' : '/projectPro/save'
      }).then(res => {
        if (res.code === '200'){
          //保存成功
          this.$message.success('保存成功')
          this.formVisible = false;
          this.load(this.pageNum)
        }else {
          this.$message.error(res.msg) //错误信息
          return false
        }
        //无论是否保存成功，都要把fileList清空
        this.fileList = []
      })
    },
    //新增保存
    save(){
      //校验表单
      this.$refs.formRef.validate((valid) => {
        if (valid){
          this.form.fileList = this.fileList;
          this.form.currentStep = this.currentStep+1;
          this.sendSave()
        }else {
          this.$message.warning("表单校验未通过")
        }
      })
    },
    //打开审核弹窗
    openAudit(row){
      this.auditVisible = true
      this.auditForm = row
      // 确保currentStep存在且为数字类型
      this.auditForm.currentStep = Number(this.auditForm.currentStep) || 0;
      // 加载步骤数据
      if (row.templateId) {
        this.form.templateId = row.templateId;
        this.steps = row.stepsJson;
      } else {
        this.steps = [];
        this.$message.warning('未找到模板信息，无法加载步骤');
      }
      if (row.fileListJson){
        this.fileList = row.fileListJson
      }else {
        this.fileList = []
      }
    },
    //开始按钮
    isStart(currentStep){
      return currentStep === 0;
    },
    //打开确认弹窗
    openConfirm(row){
      this.confirmVisible = true
      this.confirmForm = row
      // 确保currentStep存在且为数字类型
      this.confirmForm.currentStep = Number(this.confirmForm.currentStep) || 0;
      // 加载步骤数据
      if (row.templateId) {
        this.form.templateId = row.templateId;
        this.steps = row.stepsJson;
      } else {
        this.steps = [];
        this.$message.warning('未找到模板信息，无法加载步骤');
      }
      if (row.fileListJson){
        this.fileList = row.fileListJson
      }else {
        this.fileList = []
      }
    },
    //单个删除
    handleDel(row){
      this.$confirm('确认删除《'+row.projectName+'》吗？','确认删除',{type: "warning"}).then(ok => {
        this.$request.delete('/projectPro/delete/'+row.id).then(res => {
          if (res.code == '200'){
            this.$message.success("删除成功")
          }else {
            this.$message.error("删除失败："+res.msg)
          }
          this.load(this.pageNum) //刷新表格
        })
      }).catch(() => {}) //catch捕捉先不做处理
    },
    //批量删除之前--多选框，参数是选中的行对象
    handleSelectionChange(rows){
      this.ids = rows.map(row => row.id) //流和表达式，将行id提取出来存入数组
    },
    //批量删除
    handleDelBatch(){
      //校验：点击批量删除按钮之前，未选择多选框时提示
      if (!this.ids.length){
        this.$message.warning('请选择需要批量删除的记录！')
        return
      }
      this.$confirm('你确认批量删除['+this.ids+']这些记录吗？','确认删除',{type: "warning"}).then(ok => {
        this.$request.delete('/projectPro/deleteBatch',{data: this.ids}).then(res => {
          if (res.code == '200'){
            this.$message.success("批量删除成功")
          }else {
            this.$message.error("批量删除失败:"+res.msg)
          }
          this.load(this.pageNum) //刷新表格
        })
      }).catch(() => {}) //catch捕捉先不做处理
    },
    //是否公开 改变事件
    openChange(form){
      // this.form = form; //这样不合适，是属于直接指向内存地址，浅拷贝会直接改变影响数据库原本数据
      this.form = JSON.parse(JSON.stringify(form))  //变为与行对象没有关系，而是重新赋值，新建自己的内存空间，互不影响，属于深拷贝
      //调用更新，无需校验，直接发请求
      this.sendSave()
    },

    getStatusText(row) {
      // 参数校验
      if (!row || typeof row.currentStep !== 'number' || !row.stepsJson || !Array.isArray(row.stepsJson)) {
        return '未开始';
      }
      // 在row对象的steps中查找当前步骤
      const step = row.stepsJson.find(item => item.step === row.currentStep);
      
      // 使用可选链安全地访问stepName属性，避免undefined错误
      return step?.stepName || '未开始';
    },
    getStatusType(row) {
      switch (this.getStatusText(row)) {
        case '未开始':
          return 'info';
        default:
          return ''; // 默认没有特殊样式
      }
    },
    //向接口发送
    sendApi(){
      this.$request({
        //有id就是编辑
        method: this.form.id ? 'PUT' : 'POST',
        data: this.form,
        url: this.form.id ? '/projectPro/update' : '/projectPro/save',
      }).then((res) => {
        if (res.code === '200') {
          //保存成功
          // this.$message.success('操作成功')
          this.formVisible = false
          this.load(this.pageNum)
        } else {
          this.$message.error(res.msg) //错误信息
          return false
        }
        //无论是否保存成功，都要把fileList清空
        this.fileList = []
      })
    },
    //是接收人
    isRecipient(row){
      return true;
      //是否是接收人,并且接收状态不是最后一个8
      // return (row.currentStep !== 8) && (row.recipient === this.user.id);   //需要打开
      //是否是接收人,并且接收状态是未接收
      // return (row.state === 6) && (row.recipient === this.user.id);
    },
    //是否是审核人
    isAudit(row){
      // 检查是否为审核人且当前步骤为审核类型
      // 验证必要参数存在
      if (!row || !this.user || !row.stepsJson || !row.currentStep) {
        return false;
      }
      
      // 当前用户是否为接收人
      const isRecipient = (row.recipient === this.user.id);
      
      // 当前步骤是否为审核类型(stepType === 2)
      const currentStepInfo = row.stepsJson.find(item => item.step === row.currentStep);
      const isAuditStep = currentStepInfo && currentStepInfo.stepType === 2;
      
      return isRecipient && isAuditStep;
    },
    /**
     * 判断是否允许编辑当前流程步骤
     * @param {Object} row 流程数据行
     * @returns {boolean} 是否允许编辑
     */
    allowEdit(row){
      // 验证必要参数存在性
      if (!row || !this.user || !row.stepsJson || typeof row.currentStep !== 'number') {
        return false;
      }
      
      // 检查是否为接收人
      const isRecipient = (row.recipient === this.user.id);
      
      // 缓存当前步骤配置，避免重复计算
      const currentStepConfig = row.stepsJson.find(item => item.step === row.currentStep);
      
      // 检查当前步骤类型是否为可编辑类型(1表示步骤)
      const isEditableStepType = (currentStepConfig?.stepType === 1);
      
      return isRecipient && isEditableStepType;
    },

    //确认完成
    handleConfirm(row){
      // 确保row和row.currentStep存在且有效
      if (!row || typeof row.currentStep !== 'number') {
        this.$message.error('无效的流程数据');
        return;
      }
      if (this.isRecipient(row)){
        // 更新表单数据
        this.form = { ...row };
        const nextStep = row.currentStep + 1;
        this.form.currentStep = nextStep;
        // 从row.stepsJson中找出step等于nextStep的元素的handler，赋值给recipient
        this.form.recipient = row.stepsJson?.find(item => item.step === nextStep)?.handler || '';
        // 将留言内容添加到表单数据中
        this.form.confirmMessage = this.confirmForm.confirmMessage;
        // 清空留言输入框
        this.confirmForm.confirmMessage = '';
        this.form.isNodeProcess = true; //是流程节点，后端存储相关信息
        
        // 提交到API
        this.sendApi();
        this.$message.success("操作成功");
      } else {
        this.$message.error(`你可能不是《${stepName}》节点的负责人，请核对`);
      }
      this.confirmVisible = false;
    },
    
    /**
     * 预测下一步负责人
     * @param {Object} row - 当前流程记录
     * @returns {string} 下一步负责人名称
     */
    predictNextResponsiblePerson(row) {
      if (!row || typeof row.currentStep !== 'number') {
        return '未知负责人';
      }
      
      const nextStep = row.currentStep + 1;
      // 优先使用row.steps查找，如不存在则回退到this.steps
      const nextStepObj = row.stepsJson?.find(item => item.step === nextStep) || 
                          this.steps.find(step => step.step === nextStep);
      
      if (!nextStepObj) {
        return '未知步骤';
      }
      
      const user = this.userOptions.find(user => user.value === nextStepObj.handler);
      return user ? user.label : '未知负责人';
    },
    //初始化用户选择框
    initUsersOptions() {    
      this.$request({    
        method: 'GET',    
        url: '/user/getSelect',    
      }).then((res) => {    
        if (res.code === '200') {    
          this.userOptions = res.data    
        } else {    
          this.$message.error(res.msg) //错误信息    
          return false    
        }    
      })    
    },    
    // 处理自动编号勾选变化    
    handleAutoGenerateNumChange() {    
      if (this.autoGenerateNum) {    
        // 生成系统时间编号    
        const now = new Date();    
        const year = now.getFullYear();    
        const month = String(now.getMonth() + 1).padStart(2, '0');    
        const day = String(now.getDate()).padStart(2, '0');    
        const hours = String(now.getHours()).padStart(2, '0');    
        const minutes = String(now.getMinutes()).padStart(2, '0');    
        const seconds = String(now.getSeconds()).padStart(2, '0');    
        const milliseconds = String(now.getMilliseconds()).padStart(3, '0');    
        
        this.form.projectNum = 'sg'+`${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;    
      } else {    
        // 取消勾选时清空项目编号    
        this.form.projectNum = '';    
      }    
    },    
  }
}
</script>

<style>
</style>